using System;
using VixCOM;

namespace Weever.VmWare
{
    public static class Library
    {
        private static readonly VixLib _lib = new VixLib();

        public static Host Connect(ServiceProvider serviceProvider, string hostName, int hostPort, string userName, string userPassword)
        {
            IJob job =
                _lib.Connect( Constants.VIX_API_VERSION
                            , (int) serviceProvider
                            , hostName
                            , hostPort
                            , userName
                            , userPassword
                            , 0
                            , null
                            , null );

            IHost host = (IHost)Wait(job)[0];

            return new Host(host);
        }

        public static Host Connect(ServiceProvider serviceProvider)
        {
            return Connect(serviceProvider, null, 0, null, null);
        }

        internal static void Wait(IJob job, object properties, ref object results)
        {
            CheckError(job.Wait(properties, ref results));
        }

        internal static object [] Wait(IJob job)
        {
            object[] data = { Constants.VIX_PROPERTY_JOB_RESULT_HANDLE };
            object results = null;
            Wait(job, data, ref results);
            return (object[]) results;
        }

        internal static void WaitWithoutResults(IJob job)
        {
            CheckError(job.WaitWithoutResults());
        }

        private static void CheckError(ulong err)
        {
            if (_lib.ErrorIndicatesSuccess(err))
                return;

            string errorMessage = string.Format("Error ({0})", err);
            try
            {
                errorMessage = string.Format("{0} ({1})", _lib.GetErrorText(err, null), err);
            }
            catch
            {
            }
            throw new ApplicationException(errorMessage);
        }
    }
}
